<template>
    <div ref="topDiv">
        <Split v-model="split1" style="height: 100%; " class="demo-split">
            <div slot="left" style="height: 100%; overflow-y: auto; overflow-x: hidden; padding: 5px">
                <Row :gutter="16">
                    <i-col span="24">
                        <Input v-model="value" placeholder="请输入隐患条目分类..." style="width: 100%" suffix="ios-search" @on-enter='searchTree(value, apsgTree)' clearable @on-clear="clearTree"/>
                    </i-col>
                </Row>
                <Tree ref="tree" :data="apsgTree" :load-data="handleLoadData" :render="renderContent" style="width: 100%">
                    <template slot="contextMenu">
                        <DropdownItem v-if="ifAddItem" @click.native="toAddChildrenType">添加条目</DropdownItem>
                        <DropdownItem v-if="ifImportItem" @click.native="apsgImportView= true">导入条目</DropdownItem>
                        <DropdownItem v-if="ifImportItem" @click.native="exportModal">下载模板</DropdownItem>

                        <DropdownItem v-if="ifExportItem" @click.native="openExportDialog">导出条目</DropdownItem>
                        <DropdownItem v-if="ifDistributionItem" @click.native="toRelateOrg">分配条目</DropdownItem>

                        <DropdownItem v-if="ifEditItem" @click.native="toEdit">修改条目</DropdownItem>
                        <DropdownItem v-if="ifRemoveItem" @click.native="deleteApsgItemType" style="color: #ed4014">删除条目</DropdownItem>
                    </template>
                </Tree>
            </div>
            <div slot="right" class="demo-split-pane">
                <Form :label-width="90" ref="formInline" :model="formInline">
                    <Row :gutter="16" class="query-form">
                        <i-col span="8">
                            <FormItem label="隐患编号：" prop="name">
                                <Input v-model="formInline.name"  placeholder="请填写隐患编号"/>
                            </FormItem>
                        </i-col>
                        <i-col span="8">
                            <FormItem label="排查内容：" prop="remark">
                                <Input v-model="formInline.remark" placeholder="请填写排查内容"/>
                            </FormItem>
                        </i-col>
                        <i-col span="8">
                            <div style="float: right;">
                                <Button class="ivu-btn-reset" style="margin-left: 10px" @click="cancel">重置</Button>
                                <Button class="ivu-btn-query"  icon="md-search"  @click="query(selectNodeInfo.id, selectNodeInfo.type)">查询</Button>
                            </div>
                        </i-col>
                    </Row>
                    <Row class="query-form">
                        <i-col span="24">
                            <Button size="large" type="success" class="ivu-btn-add" icon="md-add"  v-if="ifAddDetail"
                                    @click="addApsgItemTypeContent">新增
                            </Button>
                        </i-col>
                    </Row>
                </Form>
                    <Table ref='table' :loading="loading" border :columns="columns" no-data-text="请选择隐患条目分类"
                           :data="infos" width="100%" :height="tableHeight2"  highlight-row stripe size="small"></Table>
                <Row type="flex" justify="end" >
                    <i-col>
                        <Page :total="pagedata.total" :current="pagedata.currentPage" :page-size="pagedata.pageSize"
                              @on-page-size-change="pageSizeChange" @on-change="pageChange" :page-size-opts="pageSizeArray" show-total show-sizer show-elevator />
                    </i-col>
                </Row>
            </div>
        </Split>
        <Modal :title="modalTitle" :transfer=false v-model="apsgItemTypeView" :width=600>
            <Form :model="formItem"   ref="formCustom"  label-position="top" :rules="ruleCustom">
                <Row type="flex" justify="space-around" class="code-row-bg">
                    <i-col span="24">
                        <FormItem label="上级分类：" prop="parentName">
                            <Input v-model="formItem.parentName" readonly></Input>
                        </FormItem>
                    </i-col>
                </Row>
                <Row type="flex" justify="space-around" class="code-row-bg">
                    <i-col span="24">
                        <FormItem label="分类名称：" prop="name">
<!--                            <cascaderDom v-if="formItem.parentId == 1" ref='queryOrgCascader1' @setOrgInfo='setQueryCompanyId' @setOrgname="setQueryCompanyName" :orgTree="true" :currentOrgId = "formItem.companyId" :setCurrentName="{label:formItem.companyName, value:formItem.companyId}"></cascaderDom>-->
<!--                            <Input v-else v-model="formItem.name" maxlength="500"  show-word-limit></Input>-->

                            <Input v-model="formItem.name" maxlength="500"  show-word-limit></Input>
                        </FormItem>
                    </i-col>
                </Row>
                <Row type="flex" justify="space-around" class="code-row-bg">
                    <i-col span="24">
                        <FormItem label="描述：">
                            <Input type="textarea" v-model="formItem.desc" maxlength="255" show-word-limit></Input>
                        </FormItem>
                    </i-col>
                </Row>
            </Form>
            <div slot="footer">
                <Button type="primary" class='ivu-btn-save' :loading="buttonLoading" @click="saveOrUpdate('formCustom')">确定</Button>
                <Button type="primary" class='ivu-btn-cancel' @click="handleCancelApsgItem" style="margin-left: 2px">取消</Button>
            </div>
        </Modal>
        <Modal title="条目机构映射" :transfer=false v-model="relateOrgView" :width=1200 >
            <Split v-model="split2" style="height: 400px">
                <div slot="left" style="height: 100%; overflow-y: auto; overflow-x: hidden; padding: 5px; padding-top: 0;">
                    <Table height="400"   :columns="columns2" :data="apsgTypeOrg" border></Table>
                </div>
                <div slot="right" style="margin-left:20px;height:100%;overflow-y:auto">
                    <Select placeholder="请选择映射范围" v-model="orgType">
                        <Option value="company">集团级(全集团通用)</Option>
                        <Option value="project">公司级（本公司及其下属可用）</Option>
                        <Option value="group">部门级（仅本部门可用）</Option>
                    </Select>
                    <Tree ref="treeOrg" :data="orgTree" :load-data="loadData" show-checkbox check-strictly="true" style="font-size: 29px;overflow-x:auto;overflow-y:auto"></Tree>
                </div>
            </Split>
            <div slot="footer">
                <Button type="primary" class='ivu-btn-save' :loading="buttonLoading" @click="saveItemTypeOrg">确定</Button>
                <Button type="primary" class='ivu-btn-cancel' @click="relateOrgView = false" style="margin-left: 2px">取消</Button>
            </div>
        </Modal>
        <Modal :title="apsgItemTitle" :transfer=false v-model="apsgItemView" :width=600>
            <Form :model="apsgItemCustom"  ref="apsgItemCustom"  label-position="top" :rules="ruleCustom2">
                <Row type="flex" justify="space-around" class="code-row-bg" :gutter="16">
                    <i-col span="12">
                        <FormItem label="排查项目：" prop="idApitemclassfyName">
                            <Input v-model="apsgItemCustom.idApitemclassfyName" readonly></Input>
                        </FormItem>
                    </i-col>
                    <i-col span="12">
                        <FormItem label="隐患等级：" prop="level">
                            <Select v-model="apsgItemCustom.level" @on-change="changeLevel">
                                <Option value="Ⅰ">Ⅰ</Option>
                                <Option value="Ⅱ">Ⅱ</Option>
                                <Option value="Ⅲ">Ⅲ</Option>
                                <Option value="Ⅳ">Ⅳ</Option>
                            </Select>
                        </FormItem>
                    </i-col>
                </Row>
                <Row type="flex" justify="space-around" class="code-row-bg" :gutter="16">
                    <i-col span="12">
                        <FormItem label="整改时限（天）：" prop="recPeriod">
                            <InputNumber v-model="apsgItemCustom.recPeriod" style="width:100%"></InputNumber>
                        </FormItem>
                    </i-col>
                    <i-col span="12">
                        <FormItem label="扣分值（分）："  prop="score">
                            <Input v-model="apsgItemCustom.score" type="number"></Input>
                        </FormItem>
                    </i-col>
                </Row>
                <Row type="flex" justify="space-around" class="code-row-bg">
                    <i-col span="24">
                        <FormItem label="排查内容：" prop="content">
                            <Input type="textarea" v-model="apsgItemCustom.content" ></Input>
                        </FormItem>
                    </i-col>
                </Row>
                <Row type="flex" justify="space-around" class="code-row-bg">
                    <i-col span="24">
                        <FormItem label="控制措施：" prop="control">
                            <Input type="textarea" v-model="apsgItemCustom.control" ></Input>
                        </FormItem>
                    </i-col>
                </Row>
            </Form>
            <div slot="footer">
                <Button type="primary" class='ivu-btn-save' :loading="buttonLoading" @click="saveOrUpdateApsgItem('apsgItemCustom')">确定</Button>
                <Button type="primary" class='ivu-btn-cancel' @click="apsgItemView = false" style="margin-left: 2px">取消</Button>
            </div>
        </Modal>
        <Modal title="条目内容查看" class="modal-view-detail"  :transfer=false v-model="apsgItemDataView" :width=600>
            <Form :model="apsgItemCustom" :label-width="160" >
                <Row type="flex" justify="space-around" class="code-row-bg">
                    <i-col span="11">
                        <FormItem label="排查项目：" prop="idApitemclassfyName">
                            {{apsgItemData.idApitemclassfyName}}
                        </FormItem>
                    </i-col>
                    <i-col span="11">
                        <FormItem label="隐患等级：" prop="level">
                            {{apsgItemData.level}}
                        </FormItem>
                    </i-col>
                </Row>
                <Row type="flex" justify="space-around" class="code-row-bg">
                    <i-col span="11">
                        <FormItem label="整改时限（天）：" prop="recPeriod">
                            {{apsgItemData.recPeriod}}
                        </FormItem>
                    </i-col>
                    <i-col span="11">
                        <FormItem label="扣分值（分）："  prop="score">
                            {{apsgItemData.score}}
                        </FormItem>
                    </i-col>
                </Row>
                <Row type="flex" justify="space-around" class="code-row-bg">
                    <i-col span="24">
                        <FormItem label="排查内容：" prop="content">
                            {{apsgItemData.content}}
                        </FormItem>
                    </i-col>
                </Row>
                <Row type="flex" justify="space-around" class="code-row-bg">
                    <i-col span="24">
                        <FormItem label="控制措施：" prop="control">
                            {{apsgItemData.control}}
                        </FormItem>
                    </i-col>
                </Row>
            </Form>
            <div slot="footer">
                <Button class='ivu-btn-save' @click="apsgItemDataView=false">关闭</Button>
            </div>
        </Modal>
        <Modal title="条目查看"  class="modal-view-detail"  :transfer=false v-model="apsgItemTypeDataView" :width=600>
            <Form :model="viewData" :label-width="120">
                <Row type="flex" justify="space-around" class="code-row-bg">
                    <Col span="11">
                        <FormItem label="编号：" prop="code">
                            {{viewData.code}}
                        </formitem>
                    </Col>
                    <Col span="11">
                        <FormItem label="名称：" prop="name">
                            {{viewData.name}}
                        </formitem>
                    </Col>
                </Row>
                <Row type="flex" justify="space-around" class="code-row-bg">
                    <Col span="11">
                        <FormItem label="上级分类：" prop="parentName">
                            {{viewData.parentName}}
                        </formitem>
                    </Col>
                    <Col span="11">
                        <FormItem label="分类类型：">
                            {{viewData.type=="1"?"专业":
                            (viewData.type=="2"?"排查类型":
                            (viewData.type=="3"?"排查项目":
                            (viewData.type=="4"?"排查项目2":"")))}}
                        </FormItem>
                    </Col>
                </Row>
            </Form>
            <div slot="footer">
                <Button class='ivu-btn-save' @click="apsgItemTypeDataView=false">关闭</Button>
            </div>
        </Modal>
        <Modal title="导入隐患条目" v-model="apsgImportView" :transfer=false footer-hide :width=600>
            <Upload
                    ref="upload"
                    type="drag"
                    name="file"
                    :show-upload-list="false"
                    :on-success="handleSuccess"
                    :format="['xls','xlsx']"
                    :headers='{"Authorization": token}'
                    :action="fileUrl">
                <div style="padding: 20px 0">
                    <Icon type="ios-cloud-upload" size="52" style="color: #3399ff"></Icon>
                    <p><span style="color: red">*</span>&nbsp;点击将文件拖拽到这里上传</p>
                    <h3 style="padding: 10px 0;color: red; text-align: left">模板填报要求</h3>
                    <p style="color: red; text-align: left">1、尽量使用项目组提供的模板格式，不要多行、多列，不要合并行或者合并列，不要合并单元格，不要修改各列表头名称，否则系统不能识别。</p>
                    <p style="color: red; text-align: left">2、“公司名称”下的内容也可以自定义内容，比如XXX公司安全环保部、XXX公司安全环保部部长 等，导入会单独生成一个目录节点。</p>
                    <p style="color: red; text-align: left">3、每次上传附件，附件中只能有一个sheet页有内容，不支持模板内有多个页签都有内容的情况，可以把多个页签的内容都挪到第一页。</p>
                    <p style="color: red; text-align: left">4、模板内容中不能有空白项。</p>
                </div>
            </Upload>
        </Modal>
        <Modal title="导出隐患条目" v-model="apsgExportView" :transfer=false :width=600>
            <div style="height: 400px">
                <Tree ref="tree2" :data="apsgTree2" show-checkbox style="font-size: 29px;overflow-x:auto;overflow-y:auto; height:100%;"></Tree>
            </div>
            <div slot="footer">
                <Button type="primary" class='ivu-btn-save' :loading="buttonLoading" @click="exportItem">导出</Button>
                <Button type="primary" class='ivu-btn-cancel' @click="apsgExportView = false" style="margin-left: 2px">取消</Button>
            </div>
        </Modal>
        <Modal title="导入异常" v-model="ifErrorView" :transfer=false :width=600>
            <p v-html="exportError" style="height: 400px;overflow-x:auto;overflow-y:auto;color: red "></p>
            <div slot="footer">
                <Button type="primary" class='ivu-btn-cancel' @click="ifErrorView = false" >取消</Button>
            </div>
        </Modal>
    </div>
</template>
<script>
    import {sessionStorage} from '@/common/cacheUtils.js';
    let cascaderDom = () => import('@/components/cascader-dom.vue');;
    import {Api} from '../../../api/index.js'
    export default{
        components:{
            cascaderDom
        },
        data () {
            return {
                orgType: 'project',
                ifAddItem: false,
                ifEditItem: false,
                ifRemoveItem: false,
                ifAddDetail: false,
                ifImportItem: false,
                ifDistributionItem: false,
                ifExportItem: false,
                selectNode: {},
                selectRoot: [],
                selectNodeInfo:{},
                selectNode:"",
                orgTree: [],
                apsgTree2: [],
                apsgItemTitle: "",
                relateOrgView: false,
                apsgTypeOrg: [],
                apsgItemList: [],
                selectedApsgType: {},
                apsgItemData: {},
                tableHeight1: 300,
                tableHeight2: 300,
                loading3: false,
                pagedata: {
                    total: 0,
                    pageSize: 10,
                    currentPage: 1,
                },
                pageSizeArray: [10, 20, 50],
                loading: false,
                formItem: {},
                viewData: {},
                split1: 0.25,
                split2: 0.45,
                formInline: {},
                apsgItemCustom: {},
                apsgItemView: false,
                apsgItemTypeView: false,
                apsgItemDataView: false,
                apsgItemTypeDataView: false,
                apsgImportView: false,
                apsgExportView: false,
                ifErrorView: false,
                modalTitle:"",
                buttonLoading: false,
                token: sessionStorage('token').get('Authorization'),
                columns2:[
                    {
                        title: '组织机构名称',
                        align: 'center',
                        key: 'orgName',
                    },
                    {
                        title: '映射类型',
                        align: 'center',
                        key: 'orgType',
                        render:(h,params)=>{
                            return h('div',[
                                h('span',params.row.orgType == 'company' ? '二级公司级': params.row.orgType == 'project'? '项目级':params.row.orgType == 'group'? '分公司级': '--'  || '--')
                            ]);
                        }
                    },
                    {
                        title: '操作',
                        key: 'action',
                        fixed: 'right',
                        maxWidth: 270,
                        align: 'center',
                        render: (h, params) => {
                            return h('div', [
                                h('A', {
                                    props: {
                                        type: 'primary',
                                        size: 'small'
                                    },
                                    style: {
                                        fontSize: '14px',
                                        color: 'red'
                                    },
                                    on: {
                                        click: () => {
                                            this.toDeleteApsgOrg(params.row);
                                        }
                                    }
                                }, '删除'),
                            ]);
                        }
                    }
                ],
                ruleCustom: {
                    name: [{
                        required: true,
                        message: '  ',
                        trigger: 'blur, change'
                    }],
                    title: [{
                        required: true,
                        message: '  ',
                        trigger: 'blur, change'
                    }],
                    parentId: [{
                        required: true,
                        message: '  ',
                        trigger: 'blur, change'
                    }],
                    type: [{
                        required: true,
                        message: '  ',
                        trigger: 'blur, change'
                    }]
                },
                ruleCustom2: {
                    level: [{
                        required: true,
                        message: '  ',
                        trigger: 'blur, change'
                    }],
                    content: [{
                        required: true,
                        message: '  ',
                        trigger: 'blur, change'
                    }],
                    recPeriod: [{
                        required: true,
                        message: '  ',
                        trigger: 'blur, change',
                        type: 'integer'
                    }]
                },
                apsgTree: [{
                    id:'1',
                    code : '1',
                    title : '隐患条目分类',
                    type : 0,
                    parentName : '',
                    contextmenu: true,
                    children: [],
                    _loading: false,
                    _showChildren: true
                }],
                columns: [
                    {
                        type: 'index',
                        title: '序号',
                        width: 80,
                        align: 'center',
                    },
                    {
                        title: '隐患等级',
                        align: 'center',
                        key: 'level',
                        width: 100,
                        render:(h,params)=>{
                            return h('div',[
                                h('span',params.row.level || '--')
                            ]);
                        }
                    },
                    {
                        title: '排查内容',
                        align: 'center',
                        key: 'content',
                        render:(h,params)=>{
                            return h('div',[
                                h('span',params.row.content || '--')
                            ]);
                        }
                    },
                    this.getActionColumns()
                ],
                infos: [],
                view:true,
                isAdd:false,
                fileUrl: '',
                exportError: ''
            }
        },
        mounted() {
            this.$refs.topDiv.style.height = (window.innerHeight - 120) + 'px';
            this.tableHeight2 = window.innerHeight - 240;
            this.getApsgItemByParentId(this.apsgTree[0]);
            this.getOrgInfoTree();
            this.selectedApsgType = this.apsgTree[0];
            let user = sessionStorage('userId').getObject('userId');
            this.fileUrl = Api.importApsgItem + '/' + user.companyId + '/' + user.userId;
        },
        watch: {
            "apsgItemTypeView":function(qw,er){
                if(!qw){
                    this.formItem = {};
                }
            },
            "relateOrgView": function(qw, er){
                if(!qw){
                    this.orgType = 'group';
                    this.getOrgInfoTree();
                }
            },
            "apsgExportView": function (qw, er) {
                if(!qw){
                    this.apsgTree2 = [];
                }
            }
        },
        methods: {
            selectMenuItem(name){
                if(name == "addApsgItemType"){
                    this.toAddChildrenType(this.selectNodeInfo);
                }
                if(name == "editApsgItemType"){
                    this.toEdit(this.selectNodeInfo);
                }
                if(name == "relatedOrg"){
                    this.toRelateOrg(this.selectNodeInfo);
                }
                if(name == "deleteApsgItemType"){
                    this.$Modal.confirm({
                        title: '提示信息',
                        content: '<p>删除该菜单及其子菜单</p>',
                        okText:'确认',
                        cancelText:'取消',
                        onOk: () => {
                            this.$http.delete(Api.deleteApsgItem + "/"+this.selectNodeInfo.id, {params:{}
                            }).then(res=>{
                                const parentKey = this.selectRoot.find(el => el === this.selectNode).parent;
                                const parent = this.selectRoot.find(el => el.nodeKey === parentKey).node;
                                for(var i=0;i<parent.children.length;i++){
                                    if(parent.children[i].id == this.selectNodeInfo.id)
                                    {
                                        parent.children.splice(i, 1);
                                        this.$Message.success('删除成功');
                                        return ;
                                    }
                                }
                            }).catch(e => {
                                this.$Message.error('请求失败');
                            })
                        }
                    })
                }
            },
            addApsgItemTypeContent(){
                let user = sessionStorage('userId').getObject('userId');
                this.apsgItemCustom = {idApitemclassfy:this.selectNodeInfo.id,
                    idApitemclassfyCode:this.selectNodeInfo.code, idApitemclassfyName:this.selectNodeInfo.title, name: this.selectNodeInfo.code, createUserId: user.userId};
                this.apsgItemTitle = "条目内容新增"
                this.apsgItemView = true;
                this.isAdd = true;
            },
            loadData(item, callback) {
                item.loading3 = true;
                this.$http.get(Api.queryOrg, {
                    params: {
                        parentId: item.orgId,
                        codeAffordIf : 0
                    }
                }).then(res => {
                    item.loading3 = false;
                    if(res.data.data.length !== 0) {
                        res.data.data.map(i => {
                            i.title = i.orgName
                            delete i['orgName']
                            i.loading = false;
                            i.children = [];
                        })
                        item.children = res.data.data;
                        callback(item.children);
                    } else {
                        delete item['children'];
                        delete item['loading'];
                    }
                }).catch(e => {
                    this.$Message.error('请求失败');
                })
            },
            treechange(data, item) {
                var req = {};
                req.itemTypeId = this.selectedApsgType.id;
                req.orgId = item.orgId;
                req.orgName = item.title;
                this.$http.post(Api.saveApsgItemOrg,req).then(res => {
                    this.apsgTypeOrg.unshift(req);
                }).catch(e => {
                    this.$Message.error('请求失败');
                })
            },
            handleLoadData (item, callback) {
                // setTimeout(() => {
                    this.$http.get(Api.getApsgItemOrgType, {params:{parentId:item.id, itemType: item.itemType}}).then(res => {
                        callback(res.data);
                    }).catch(e => {
                        this.$Message.error('请求失败');
                    })
                // }, 2000);
            },
            apsgTableCellDbClick(row, index){
                this.query(row.id,row.type);
            },
            apsgTableCellClick(row,index){
            },
            getApsgItemByParentId(parent){
                let user = sessionStorage('userId').getObject('userId');
                let form = {
                    parentId: parent.id,
                    orgId: user.orgInfo.orgId,
                    companyId: user.companyId,
                    orgLevel: user.orgInfo.orgLevel,
                    twoLevelOrgId: user.twoLevelOrgId,
                    itemType: this.selectNodeInfo.itemType
                };
                this.$http.get(Api.getApsgItemOrgType, {params: form}).then(res => {
                    res.data.map((i=>{
                        if(user.userId == i.createUserId || user.userId == '8ad810e24f39585c014f395aae380000') i.contextmenu = true;
                        else i.contextmenu = false;
                    }));
                    this.$set(parent,'children',res.data);
                    this.$set(parent,'expand',true);
                }).catch(e => {
                    this.$Message.error('请求失败');
                })
            },
            pageSizeChange(pageSize){
                this.pagedata.pageSize = pageSize;
                this.query(this.selectNodeInfo.id,this.selectNodeInfo.type);
            },
            pageChange(pageNum){
                this.pagedata.currentPage = pageNum;
                this.query(this.selectNodeInfo.id,this.selectNodeInfo.type);
            },
            saveOrUpdate(name){
                this.$refs[name].validate((valid) => {
                    if (valid) {
                        this.buttonLoading = true
                        if(this.isAdd){
                            this.formItem.id = this.uuid();
                            if(this.formItem.type == 1){
                                let num = '';
                                for(let i=0;i<11;i++){
                                    num+=Math.floor(Math.random()*10);
                                }
                                this.formItem.code = num;
                            }
                            this.$http.post(Api.saveApsgType, this.formItem).then(res => {
                                this.buttonLoading = false
                                this.formItem.title = this.formItem.name;
                                this.formItem.loadng = false;
                                this.formItem._loadng = false;
                                this.selectRoot.find(el => {
                                    if(el === this.selectNode){
                                        el.node.expand = true;
                                        if(this.selectNodeInfo.type ==  0){
                                            this.getApsgItemByParentId(el.node);
                                        }else{
                                            this.getApsgItemChildren(el.node);
                                        }
                                        this.$Message.success('成功');
                                        this.apsgItemTypeView = false;
                                    }
                                })
                            }).catch(e => {
                                this.$Message.error('请求失败');
                            })
                        }else{
                            this.$http.put( Api.updateApsgType, this.formItem).then(res => {
                                this.buttonLoading = false
                                this.formItem.title = this.formItem.name;
                                // this.selectedApsgType = Object.assign(this.selectedApsgType, JSON.parse(JSON.stringify(this.formItem)));
                                this.$set(this.selectNodeInfo,'title', this.formItem.title);
                                this.apsgItemTypeView = false;
                                this.$Message.success('成功');
                            }).catch(e => {
                                this.$Message.error('请求失败');
                            })
                        }
                    } else {
                        this.$Message.error('Fail!');
                    }
                })
            },
            saveOrUpdateApsgItem(name){
                this.$refs[name].validate((valid) => {
                    if (valid) {
                        this.buttonLoading = true
                        if(this.isAdd){
                            this.apsgItemCustom.id = this.uuid();
                            this.$http.post(Api.saveApsgItem, this.apsgItemCustom).then(res => {
                                this.buttonLoading = false
                                this.apsgItemView = false;
                                this.query(this.selectNodeInfo.id,this.selectNodeInfo.type);
                            }).catch(e => {
                                this.$Message.error('请求失败');
                            })
                        }else{
                            let num = '';
                            for(let i=0;i<11;i++){
                                num+=Math.floor(Math.random()*10);
                            }
                            this.apsgItemCustom.name=num;
                            this.$http.put( Api.updateApsgItem, this.apsgItemCustom).then(res => {
                                this.buttonLoading = false
                                this.query(this.selectNodeInfo.id,this.selectNodeInfo.type);
                                this.apsgItemView = false;
                                this.$Message.success('成功');
                            }).catch(e => {
                                this.$Message.error('请求失败');
                            })
                        }
                    } else {
                        this.$Message.error('Fail!');
                    }
                })
            },
            getApsgItemChildren(parent){
                let form = {
                    parentId: parent.id,
                    itemType: parent.itemType
                };
                this.$http.get(Api.getApsgItemOrgType, {params: form}).then(res => {
                    this.$set(parent,'children',res.data);
                }).catch(e => {
                    this.$Message.error('请求失败');
                })
            },
            getOrgInfoTree(){
                this.orgTree = [];
                this.$http.get(Api.queryOrg, {
                    params: {
                        parentId: -1,
                        codeAffordIf : 0
                    }
                }).then(res => {
                    res.data.data.map(i => {
                        i.title = i.orgName;
                        delete i['orgName'];
                        i.loading = false;
                        i.children = [];
                    })
                    this.orgTree.push(res.data.data[0]);
                }).catch(e => {
                    this.$Message.error('请求失败');
                })
            },
            handleCancel() {
                this.apsgItemTypeView = false;
            },
            handleCancelApsgItem() {
                this.laoding = false;
                this.apsgItemTypeView = false;
            },
            toAddChildrenType(){
                let user = sessionStorage('userId').getObject('userId');
                this.modalTitle = '隐患条目新增';
                this.formItem = {
                    parentName: this.selectNodeInfo.title,
                    parentId: this.selectNodeInfo.id,
                    code: this.selectNodeInfo.code,
                    type: Number(this.selectNodeInfo.type) +1,
                    orgId: user.companyId,
                    companyName: user.companyName,
                    companyId: user.companyId,
                    createUserId: user.userId,
                    name: user.companyName
                };
                this.apsgItemTypeView = true;
                this.isAdd = true;
            },
            deleteApsgItemType(){
                this.$Modal.confirm({
                    title: '提示信息',
                    content: '<p>删除该菜单及其子菜单</p>',
                    okText:'确认',
                    cancelText:'取消',
                    onOk: () => {
                        let user = sessionStorage('userId').getObject('userId');
                        this.$http.delete(Api.deleteApsgItem + "/"+this.selectNodeInfo.code, {params:{userId: user.userId}
                        }).then(res=>{
                            const parentKey = this.selectRoot.find(el => el === this.selectNode).parent;
                            const parent = this.selectRoot.find(el => el.nodeKey === parentKey).node;
                            for(let i=0;i<parent.children.length;i++){
                                if(parent.children[i].id == this.selectNodeInfo.id)
                                {
                                    parent.children.splice(i, 1);
                                    this.$Message.success('删除成功');
                                    return ;
                                }
                            }
                        }).catch(e => {
                            this.$Message.error('请求失败');
                        })
                    }
                })
            },
            toEdit(){
                let user = sessionStorage('userId').getObject('userId');
                this.$http.get(Api.apsgItemTypeById + "/" + this.selectNodeInfo.id).then(res => {
                    this.modalTitle = "条目修改";
                    this.formItem = res.data;
                    this.formItem.companyName = res.data.name;
                    this.formItem.updateUserId = user.userId;
                    this.apsgItemTypeView = true;
                    this.isAdd = false;
                }).catch(e => {
                    this.$Message.error('请求失败');
                })
            },
            toViewData(row){
                this.$http.get(Api.apsgItemTypeById + "/" + row.id).then(res => {
                    this.viewData  = res.data;
                    this.apsgItemTypeDataView = true;
                }).catch(e => {
                    this.$Message.error('请求失败');
                })
            },
            toViewApsgItem(row){
                this.apsgItemData = row;
                this.apsgItemData.idApitemclassfy = this.selectNodeInfo.id;
                this.apsgItemData.idApitemclassfyCode = this.selectNodeInfo.code;
                this.apsgItemData.idApitemclassfyName = this.selectNodeInfo.title;
                this.apsgItemDataView = true;
            },
            toEditApsgItem(row){
                this.apsgItemTitle = "条目内容编辑"
                this.apsgItemCustom = row;
                this.apsgItemCustom.idApitemclassfy = this.selectNodeInfo.id;
                this.apsgItemCustom.idApitemclassfyCode = this.selectNodeInfo.code
                this.apsgItemCustom.idApitemclassfyName = this.selectNodeInfo.title;
                let user = sessionStorage('userId').getObject('userId');
                this.apsgItemCustom.updateUserId = user.userId;
                this.apsgItemView = true;
                this.isAdd = false;
            },
            toDeleteApsgItem(row){
                this.$http.delete(Api.deleteApsgItemById + "/" + row.id).then(res => {
                    if(res.data.status == 200){
                        this.infos.splice(row._index,1);
                        this.$Message.success('请求成功');
                    }
                }).catch(e => {
                    this.$Message.error('请求失败');
                })
            },
            cancel(){
                this.formInline = {};
                this.query(this.selectNodeInfo.id, this.selectNodeInfo.type)
            },
            query(id,type){
                this.loading = true;
                let user = sessionStorage('userId').getObject('userId');
                let data = {
                    startPage: this.pagedata.currentPage,
                    pageSize: this.pagedata.pageSize,
                    idApitemclassfy: id,
                    aptype: type,
                    orgId: user.orgInfo.orgId
                };
                data = Object.assign(data,JSON.parse(JSON.stringify(this.formInline)));
                this.$http.get(Api.apsgItem, {params: data}).then(res => {
                    this.infos = res.data.data;
                    this.pagedata.total = res.data.totalSize;
                    this.loading = false;
                }).catch(e => {
                    this.$Message.error('请求失败');
                })
            },
            toRelateOrg(){
                this.$http.get(Api.getApsgItemTypeOrgByTypeId + "/" + this.selectNodeInfo.id).then(res => {
                    this.apsgTypeOrg  = res.data.data;
                    this.relateOrgView = true;
                }).catch(e => {
                    this.$Message.error('请求失败');
                })
            },
            toDeleteApsgOrg(row){
                this.$http.delete(Api.deleteApsgItemOrg + "/" + row.id).then(res => {
                    if(res.data.status == 200){
                        this.apsgTypeOrg.splice(row._index,1);
                        this.$Message.success({content: '保存成功', duration: 4});
                    }
                }).catch(e => {
                    this.$Message.error('删除失败');
                })
            },
            changeLevel(id){
                if(id == 'Ⅳ'){
                    this.apsgItemCustom.recPeriod = 2;
                }else if(id == 'Ⅲ'){
                    this.apsgItemCustom.recPeriod = 5;
                }else if(id == 'Ⅱ'){
                    this.apsgItemCustom.recPeriod = 10;
                }else if(id == 'Ⅰ'){
                    this.apsgItemCustom.recPeriod = 30;
                }
            },
            setQueryCompanyId(data) {
                this.$set(this.formItem, 'orgId', data[data.length - 1])
            },
            setQueryCompanyName(name) {
                this.$set(this.formItem, 'name', name)
            },
            getActionColumns(noRender){
                return {
                    title: '操作',
                    key: 'action',
                    fixed: 'right',
                    maxWidth: 160,
                    align: 'center',
                    render: (h, params) => {
                        if (noRender instanceof Function && noRender(params)) {
                            return;
                        }
                        if (this.selectNodeInfo.itemType === "company") {
                            return h('div', [
                                h('A', {
                                    props: {
                                        type: 'primary',
                                        size: 'small'
                                    },
                                    style: {
                                        fontSize: '14px',
                                        color: params.row.code == "1" ? '#d0d0d0' : '',
                                        pointerEvents: params.row.code == "1" ? 'none' : ''
                                    },
                                    on: {
                                        click: () => {
                                            this.toViewApsgItem(params.row);
                                        }
                                    }
                                }, '详情'),
                            ]);
                        }else{
                            return h('div', [
                                h('A', {
                                    props: {
                                        type: 'primary',
                                        size: 'small'
                                    },
                                    style: {
                                        fontSize: '14px',
                                        color: params.row.code == "1" ? '#d0d0d0' : '',
                                        pointerEvents: params.row.code == "1" ? 'none' : ''
                                    },
                                    on: {
                                        click: () => {
                                            this.toViewApsgItem(params.row);
                                        }
                                    }
                                }, '详情'),
                                h('Divider', {
                                    props: {
                                        type: 'vertical',
                                    }
                                }, ''),
                                h('A', {
                                    props: {
                                        type: 'primary',
                                        size: 'small'
                                    },
                                    style: {
                                        fontSize: '14px',
                                        color: params.row.code == "1" ? '#d0d0d0' : '',
                                        pointerEvents: params.row.code == "1" ? 'none' : ''
                                    },
                                    on: {
                                        click: () => {
                                            this.toEditApsgItem(params.row);
                                        }
                                    }
                                }, '修改'),
                                h('Divider', {
                                    props: {
                                        type: 'vertical',
                                    }
                                }, ''),
                                h('A', {
                                    props: {
                                        type: 'primary',
                                        size: 'small'
                                    },
                                    style: {
                                        fontSize: '14px',
                                        color: params.row.code == "1" ? '#d0d0d0' : 'red',
                                        pointerEvents: params.row.code == "1" ? 'none' : ''
                                    },
                                    on: {
                                        click: () => {
                                            this.toDeleteApsgItem(params.row);
                                        }
                                    }
                                }, '删除'),
                            ]);
                        }

                    }
                }
            },
            uuid() {
                let s = [];
                let hexDigits = "0123456789abcdef";
                for (var i = 0; i < 36; i++) {
                    s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
                }
                s[14] = "4"; // bits 12-15 of the time_hi_and_version field to 0010
                s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1); // bits 6-7 of the clock_seq_hi_and_reserved to 01
                s[8] = s[13] = s[18] = s[23] = "-";
                let uuid = s.join("");
                return uuid;
            },
            renderContent (h, { root, node, data }) {
                let icon = "ios-folder";
                return h('span', {
                        style: {
                            display: 'inline-block',
                            cursor: "pointer",
                            color: node.node.selected ? "#2d8cf0" : "black" //根据选中状态设置样式
                        },
                        on:{
                            click: () => {
                                this.selectNodeInfo = data;
                                if(this.selectNodeInfo.id != 1){
                                    this.query(this.selectNodeInfo.id,this.selectNodeInfo.type);
                                }
                                if (!node.node.selected)  this.$refs.tree.handleSelect(node.nodeKey);
                                if(this.selectNodeInfo.type == 4){
                                    this.ifAddDetail = true;
                                    this.tableHeight2 = window.innerHeight - 280;
                                }else{
                                    this.ifAddDetail = false;
                                    this.tableHeight2 = window.innerHeight - 240;
                                }
                            },
                            //右键点击事件
                            contextmenu: (e) => {
                                e.preventDefault();
                                this.selectNodeInfo = data;
                                this.selectRoot = root;
                                this.selectNode = node;
                                if(data.type == 0 ){
                                    this.ifAddItem = true;
                                    this.ifImportItem = true;
                                    this.ifExportItem = true;
                                    this.ifDistributionItem = false;
                                    this.ifEditItem = false;
                                    this.ifRemoveItem = false;
                                }else if(data.type == 1 ){
                                    this.ifAddItem = false;
                                    this.ifImportItem = false;
                                    this.ifExportItem = false;
                                    this.ifDistributionItem = true;
                                    this.ifRemoveItem = true;
                                    this.ifEditItem = true;
                                    this.ifShowButton();
                                }else if(data.type == 3){
                                    this.ifAddItem = true;
                                    this.ifImportItem = false;
                                    this.ifExportItem = false;
                                    this.ifDistributionItem = false;
                                    this.ifShowButton();
                                }else if(data.type == 2){
                                    this.ifAddItem = true;
                                    this.ifImportItem = false;
                                    this.ifExportItem = false;
                                    this.ifDistributionItem = false;
                                    this.ifShowButton();
                                }else if(data.type == 4){
                                    this.ifAddItem = false;
                                    this.ifImportItem = false;
                                    this.ifExportItem = false;
                                    this.ifDistributionItem = false;
                                    this.ifShowButton();

                                }
                            },
                        }
                    },
                    [
                        h('span', [
                            h('Icon', {
                                props: {
                                    type: icon,
                                },
                                style: {
                                    marginRight: '5px',
                                    color: '#FF7F00'
                                }
                            }),
                            h('span', data.title)
                        ])
                    ]
                );
            },
            handleSuccess(res, file){
                if(res.status == 200){
                    this.$Notice.success({
                        title: '隐患条目导入成功',
                    });
                    this.selectRoot.find(el => {
                        if(el === this.selectNode){
                            el.node.expand = true;
                            if(this.selectNodeInfo.type ==  0){
                                this.getApsgItemByParentId(el.node);
                            }else{
                                this.getApsgItemChildren(el.node);
                            }
                            this.$Message.success({content: '导入成功', duration: 4});
                            this.apsgItemTypeView = false;
                        }
                    })
                }else{
                    this.ifErrorView = true;
                    this.exportError = res.data;
                    // this.$Message.error({content: '导入失败，请仔细查看模板填报要求，检查导入模板是否违规！' + res.data, duration: 4});

                }
            },
            saveItemTypeOrg(){
                if(this.$refs.treeOrg.getCheckedNodes() != 0){
                    let orgIds = '';
                    this.$refs.treeOrg.getCheckedNodes().forEach(item=>{
                        orgIds += item.orgId + ',';
                    })
                    let data = {
                        orgId: orgIds,
                        itemTypeId: this.selectNodeInfo.id,
                        orgType: this.orgType
                    }
                    this.$http.post(Api.saveApsgItemOrg, data).then(res => {
                        if(res.data.status == 200){
                            this.toRelateOrg();
                            this.$Message.success({content: '保存成功', duration: 4});
                        }else{
                            this.$Message.error({content: '请求失败', duration: 4});
                        }
                    }).catch(e => {
                        this.$Message.error({content: '请求失败', duration: 4});
                    })
                }else{
                    this.$Message.error({content: '请选择组织机构', duration: 4 });
                }
            },
            searchTree(value, arr){
                let children = arr[0].children;
                let newarr = [];
                children.forEach(element => {
                    if (element.title.indexOf(value) > -1) {
                        newarr.push(element);
                    }
                });
                this.apsgTree[0].children = newarr;
            },
            clearTree(){
                let user = sessionStorage('userId').getObject('userId');
                let form = {
                    parentId: 1,
                    orgId: user.orgInfo.orgId,
                    companyId: user.companyId,
                    orgLevel: user.orgInfo.orgLevel,
                    twoLevelOrgId: user.twoLevelOrgId,
                    itemType: 0
                };
                this.$http.get(Api.getApsgItemOrgType, {params: form}).then(res => {
                    this.$set(this.apsgTree[0],'children',res.data);
                    this.$set(this.apsgTree[0],'expand',true);
                }).catch(e => {
                    this.$Message.error('请求失败');
                })
            },
            openExportDialog(){
                this.apsgExportView = true;
                this.apsgTree[0].children.forEach(item=>{
                    this.apsgTree2.push(item);
                })
            },
            ifShowButton(){
                if(user.userId == this.selectNodeInfo.createUserId || user.userId == '8ad810e24f39585c014f395aae380000'){
                    this.ifRemoveItem = true;
                    this.ifEditItem = true;
                }else{
                    this.ifRemoveItem = false;
                    this.ifEditItem = false;
                }
            },
            exportItem(){
                if(this.$refs.tree2.getCheckedNodes().length == 0){
                    this.$Message.error('请选择导出条目！');
                    return;
                }
                let itemTypes = '';
                this.$refs.tree2.getCheckedNodes().forEach(item=>{
                    itemTypes += item.id + ',';
                })
                this.buttonLoading = true;
                this.$Loading.start();
                this.$http.get(Api.apsgItem + '/export',{
                    params: {
                        typeIds: itemTypes,
                        modelType: 1
                    },
                    responseType: 'arraybuffer'
                }).then((res) => {
                    const aLink = document.createElement("a");
                    let blob = new Blob([res.data], {
                        type: "application/vnd.ms-excel"
                    })
                    aLink.href = URL.createObjectURL(blob);
                    aLink.download = "隐患条目明细.xlsx" //标题
                    aLink.click();
                    document.body.appendChild(aLink);
                    this.$Loading.finish();
                    this.buttonLoading = false;
                })
            },
            exportModal(){
                this.buttonLoading = true;
                this.$Loading.start();
                this.$http.get(Api.apsgItem + '/export',{
                    params: {
                        typeIds: '',
                        modelType: 2
                    },
                    responseType: 'arraybuffer'
                }).then((res) => {
                    const aLink = document.createElement("a");
                    let blob = new Blob([res.data], {
                        type: "application/vnd.ms-excel"
                    })
                    aLink.href = URL.createObjectURL(blob);
                    aLink.download = "企业隐患条目导入模板.xlsx" //标题
                    aLink.click();
                    document.body.appendChild(aLink);
                    this.$Loading.finish();
                    this.buttonLoading = false;
                })
            }
        },
    }
</script>
<style>
    @import './../../../index.css';
    .demo-split{
        height: 200px;
        border: 1px solid #dcdee2;
    }
    .demo-split-pane{
        padding: 10px;
    }
    .test-5::-webkit-scrollbar {
        /*滚动条整体样式*/
        width : 10px;  /*高宽分别对应横竖滚动条的尺寸*/
        height: 1px;
    }
    .test-5::-webkit-scrollbar-thumb {
        /*滚动条里面小方块*/
        border-radius   : 10px;
        background-color: skyblue;
        background-image: -webkit-linear-gradient(
                45deg,
                rgba(255, 255, 255, 0.2) 25%,
                transparent 25%,
                transparent 50%,
                rgba(255, 255, 255, 0.2) 50%,
                rgba(255, 255, 255, 0.2) 75%,
                transparent 75%,
                transparent
        );
    }
    .test-5::-webkit-scrollbar-track {
        /*滚动条里面轨道*/
        box-shadow   : inset 0 0 5px rgba(0, 0, 0, 0.2);
        background   : #ededed;
        border-radius: 10px;
    }
</style>
